package com.oreilly.ez.web;


import com.oreilly.ez.entity.SysUser;
import com.oreilly.ez.repo.SysUserRepo;
import com.oreilly.ez.util.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

//@RestController
@Slf4j
@Controller
@Validated
public class LoginCtrl {


    @Autowired
    private SysUserRepo userRepo;

    @RequestMapping("/toLogin")
    public Object toLogin(){
//        ModelAndView mav = new ModelAndView();
//        mav.setViewName("login");

        return "login";
    }
    @RequestMapping("/home")
    public Object home(){

        return "home";
    }


    @RequestMapping("/{domain}Home")
    public Object walle(@PathVariable String domain){

        Assert.notNull(domain, "路径不能为空");
        return domain + "Home";
    }

    @RequestMapping("/fail")
    public Object fail(){

        return "fail";
    }

//    @ResponseBody
    @PostMapping("/login")
    public Object login(@Valid SysUser sysUser, HttpSession session, HttpServletResponse response) throws Exception {

//        Assert.isNull(pin, "登录标识不能为空");
        String pin = sysUser.getPin();

        log.info("pin = {}", pin);
        SysUser user = userRepo.findByPin(pin);
        if(user == null){

//            throw  new BusinessException("用户不存在");
            return "redirect:fail";
        }

        log.info("user = {}", user);
        session.setAttribute("USER", user);
        String token = JwtToken.createToken(user.getPin());
        response.setHeader("X-Authorization", token);


//        Cookie cookie = new Cookie("X-Authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c");
        Cookie cookie = new Cookie("X-Authorization", token);

        // 1 day
        cookie.setMaxAge(24*60*60);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
//        return R.ok(user);

        return "redirect:appHome";
    }

    @RequestMapping("/logout")
    public Object logout(HttpSession session){

       session.removeAttribute("USER");
       return "redirect:/login";

    }


}
